<?php
namespace App\Api\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use App\Drivers;
use JWTAuth;
use App\OrderRecord;
use App\Driver;
use App\DeliveryRecord;
use App\Http\Requests;
use App\Api\Controllers\BaseController;
use Illuminate\Support\Facades\DB;
class OrderController extends BaseController
{

    public function __construct(){
        parent::__construct();
    }

 
  /**
   *@author Arius
   *@function set star for order service
   *
   *@return success or not
   */
    public function orderStar(Request $request)
    {
		$star = $request->input('star');
		$num = $request->input('num');
		//$comment = $request->input('comment');
		
        $ownerInfo = JWTAuth::toUser();
		$ownerTel = $ownerInfo['tel'];
        $order1 = OrderRecord::where('orderNum',$num)->first();
	    $deli_order = DeliveryRecord::where('orderNum',$num)->first();
		//更新至送货订单表delivery_records
		if($deli_order){
			if($ownerTel!=$deli_order['userphone']) {
         		 return $this->returnMsg('54003','NO PERMISSION,Wrong Tel');
			}
			else{
				$this->addFinishedNum($deli_order['driverPhone'],$star);
				//$this->insertComment($comment,$deli_order['driverPhone']);
				$result = DB::table('delivery_records')->where(['driverPhone'=>$deli_order['driverPhone'],'orderNum'=>$num])
					->update(['comment'=>$star,'isAccept'=>'5']);
			}
		}
      	if ($order1) {
        	if ($ownerTel!=$order1['userphone']) {
        	  	$result = $this->returnMsg('54003','NO PERMISSION,Wrong Tel');
          		return response()->json($result);
       		 }
			else{		
				$this->addFinishedNum($order1['driverPhone'],$star);
				//$this->insertComment($comment,$order1['driverPhone']);
        		$result = DB::table('order_records')->where(['driverPhone'=>$order1['driverPhone'],'orderNum'=>$num])
					->update(['comment'=>$star,'isAccept'=>'5']);
			}	
		}

        if ($result) {
          	return  $this->returnMsg('200','set star successfully');
        }else {
          	$result = $this->returnMsg('56001','fail to update');
          	return response()->json($result);
        }
        $result = $this->returnMsg('54004','error orderNum');
        return response()->json($result);
     }


	public function addFinishedNum($driverPhone,$star)
   {
		//获得司机订单总数
		$driverInfo = Driver::where('driverPhone',$driverPhone)->first()->makeVisible('attributes')->toArray();
		$finishedNum = $driverInfo['orderFinishedNum'];
        $driverStar = DB::table('drivers')
            ->where('driverPhone',$driverPhone)
            ->value('stars');
        //update the driver 's stars
       if( $star>= 3 && $star>=5 ){
			DB::table('drivers')
            	->where('driverPhone',$driverPhone)
            	->update(['stars' => ($driverStar*($finishedNum-1)+$star)/($finishedNum)]);
		}
		else if ($star==2 ){
			$star = 1;
			DB::table('drivers')
            	->where('driverPhone',$driverPhone)
            	->update(['stars' => ($driverStar*($finishedNum-1)+$star)/($finishedNum)]);
		}
		else {
			DB::table('drivers')
            	->where('driverPhone',$driverPhone)
            	->update(['stars' => ($driverStar*($finishedNum-1)-1)/($finishedNum)]);
		}
   }
	public function insertComment($comment, $driverPhone)
  {
		if($comment){
			DB::table('drivers_comment')->insert(['driverid'=>$driverPhone,'comment'=>$comment]);
			return true;
		}else{
			return false;
		}
  }

	/**
	*@author guyi 824315402@qq.com
	*
	*@desc 送货订单评价
	*
	*@param orderNum
	**/
/*	
     public function sendOrderStar (Request $request)
    {
	$orderNum = $request->input('orderNum');
	$star = $request->input('star');
	
	//Redis::hset($orderNum,'star',$star);
	//Redis::hset($orderNum,'isAccept','5');
	
	//$order = Redis::hgetall($orderNum);
	$result = DeliveryRecord::where('orderNum',$orderNum)->update('comment',$star);
	if(result)
		return $this->returnMsg('200', 'OK');
	else 
		return $this->returnMsg('500', 'fail to update');	
	
     }	*/
	
  /**
   *@author Arius
   *@function get all record for a user by token
   *
   *@return record json
   */
    public function orderRecordList()
    {
      $user = JWTAuth::toUser();
      $tel = $user['tel'];
	$all_data = [];
	$data = Redis::hgetall('usecar:'.$tel);
	if($data){
	   if($data['isAccept']>4){   //改需求前端要求少于5不显示
		$ordering[]= ['created_at'=>$data['created_at'],/*'orderNum'=>$data['orderNum'],*/
			'from'=>$data['from'],'destination'=>$data['destination'],
			'price'=>$data['price'],/*'type'=>$data['type'],*/'isAccept'=>$data['isAccept']];
		$all_data[] = $ordering;
	    }
	}
      $orders = OrderRecord::where('userphone','=',$tel)->get(['created_at','orderNum','from','destination','time','price','isAccept']);
       if(!$orders->isEmpty()){
	foreach($orders as $order)
		$all_data[] = $order;
	
        $result = $this->returnMsg('200','ok',$all_data);
	return response()->json($result);
	}
      else return $this->returnMsg('200','null');
    }

	public function deliveryRecordList()
     {
        $user = JWTAuth::toUser();
        $tel = $user['tel'];
	$deli_orderNum = Redis::sinter('send:'.$tel);
	$order = [];
	foreach($deli_orderNum as $deli_order){
		$data = Redis::hgetall($deli_order);
		$order[]= ['created_at'=>$data['created_at'],'orderNum'=>$data['orderNum'],
			'from'=>$data['from'],'destination'=>$data['destination'],
			'price'=>$data['price'],'type'=>$data['type'],'isAccept'=>$data['isAccept']];
	}	
	$deliverys = DeliveryRecord::where('userphone',$tel)->get(['created_at','orderNum','from','destination','time','price','type','isAccept']);
	foreach($deliverys as $delivery )
		$order[] = $delivery;
	if($order){
        $result = $this->returnMsg('200','ok',$order);
	return response()->json($result);
	}
      else return $this->returnMsg('404','null');
}	
    /**
     *@author Arius
     *@function get an information by id
     *
     *
     *@return record json
     */
    public function orderRecordOne(Request $request)
    {
      $one=OrderRecord::where("orderNum","=",$request->get('num'))->first();
      $d_one = DeliveryRecord::where('orderNum',$request->input('num'))->first();
      $ownertel = JWTAuth::toUser();
      $ownertel = $ownertel['tel'];
      if ($one) {
        if ($ownertel!=$one['userphone']) {
          $result = $this->returnMsg('54003','NO permission');
          return response()->json($result);
        }
		$driverPhone = $one->driverPhone;
		$driverInfo = $this->getDriverInfo($driverPhone);
        	$result = $this->returnMsg('200','ok',['orderInfo'=>$one,'driverInfo'=>$driverInfo]);
                return response()->json($result);
      }
	else if ($d_one) {
        if ($ownertel!=$d_one['userphone']) {
          $result = $this->returnMsg('54003','NO permission');
          return response()->json($result);
        }
	$driverPhone = $d_one->driverPhone;
	$driverInfo = $this->getDriverInfo($driverPhone);
       	$result = $this->returnMsg('200','ok',['orderInfo'=>$d_one,'driverInfo'=>$driverInfo]);
        return response()->json($result);
      }else{
        $result = $this->returnMsg('54005','error id');
        return response()->json($result);
      }
    }
}

